package com.niiwoo.civet.account.service.local.openAccount2.listener;

import com.alibaba.fastjson.JSON;
import com.niiwoo.civet.account.constant.MQConstant;
import com.niiwoo.civet.account.dao.entity.OpenAccountRecord;
import com.niiwoo.civet.account.enums.OpenAccountRecordStatusEnum;
import com.niiwoo.civet.account.enums.OpenAccountWayEnum;
import com.niiwoo.civet.account.service.local.openAccount2.dto.OpenAccountEvent;
import com.niiwoo.tripod.lanmao.enums.UserRoleEnum;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class R360OListener implements OpenAccountListener {

    private static final List<OpenAccountWayEnum> INTERESTED_WAY_LIST = Arrays.asList(OpenAccountWayEnum.R360_PERSON_BIND_BANK_CARD_REGISTER, OpenAccountWayEnum.R360_GROUP_ACCOUNT_CORRELATE, OpenAccountWayEnum.R360_ACTIVATE);

    private static final List<OpenAccountRecordStatusEnum> EXCEPT_STATUS = Arrays.asList(OpenAccountRecordStatusEnum.SUCCESS, OpenAccountRecordStatusEnum.FAILURE);

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public void handle(OpenAccountEvent event) {
        OpenAccountRecord record = event.getRecord();
        boolean isBorrowAccount = UserRoleEnum.enumOf(record.getAccountRole()) == UserRoleEnum.BORROWERS;
        if (!isBorrowAccount) {
            return;
        }
        String status = OpenAccountRecordStatusEnum.SUCCESS.getValue().equals(record.getStatus()) ? "1" : "2";
        String reason = OpenAccountRecordStatusEnum.SUCCESS.getValue().equals(record.getStatus()) ? "银行卡绑定成功" : StringUtils.defaultString(event.getErrorMessage(), "银行卡绑定失败");
        Map<String, String> mq = new HashMap<>();
        mq.put("niiwoo_user_id", record.getUserId());
        mq.put("bind_status", status); // bind_status  1：成功；2：失败；
        mq.put("reason", reason); // reason 失败显示具体原因；成功：银行卡绑定成功
        log.info("融360开户###同步状态至融360, data={}", JSON.toJSONString(mq));
        rabbitTemplate.convertAndSend(MQConstant.R360_OPEN_ACCOUNT_EXCHANGE, MQConstant.R360_OPEN_ACCOUNT_ROUTING, mq);
    }

    @Override
    public boolean isExpectStatus(OpenAccountRecordStatusEnum status) {
        return EXCEPT_STATUS.contains(status);
    }

    @Override
    public boolean isInterestedOpenAccountWay(OpenAccountWayEnum way) {
        return INTERESTED_WAY_LIST.contains(way);
    }

}
